package jl.cts.objects;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import jl.cts.R;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

public class Road {

	private int heigth;
	private int width;
	private int y;
	private int x;
	private int separation;
	private int color;
	private int difficulty;

	private ArrayList<Car> cars;

	private int numCars;

	int lastCarX = 0;
	private int carsSpeedX;

	public Road(Context context, int difficulty, int x, int y, int width,
			int heigth, int color, int carsSpeedX) {
		this.carsSpeedX = carsSpeedX;
		this.heigth = heigth;
		this.width = width;
		this.color = color;
		this.y = y;
		this.x = x;
		this.difficulty = difficulty;

		init(context);

	}

	private void init(Context context) {
		cars = new ArrayList<Car>();

		switch (difficulty) {
		case 1:
			numCars = 3;
			break;
		case 2:
			numCars = 4;
			break;
		case 3:
			numCars = 4;
			break;
		case 4:
			numCars = 5;
			break;
		case 5:
			numCars = 7;
			break;
		default:
			break;
		}

		separation = width / numCars;

		for (int i = 0; i < numCars; i++) {
			Car car = new Car(context, R.drawable.car2, x + separation * i, y);
			car.setSpeed(carsSpeedX, 0);
			cars.add(car);
		}

		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				for (Car car : cars) {
					if (car.isOutOfTheRoadRight(x, width)) {
						car.setX(x - car.getWidth());
					} else {
						if (car.isOutOfTheRoadLeft(x)) {
							car.setX(x + width);
						}
					}
					if (!car.isMoving()) {
						car.setMoving(true);
					}
				}
			}
		}, 3000, 1000);
	}

	public void render(Canvas canvas, Paint paint) {

		// draw the background of the road.
		paint.setColor(color);
		canvas.drawRect(x, y, x + width, y + heigth, paint);

		// draw the border of the road.
		paint.setColor(Color.DKGRAY);
		canvas.drawRect(x, y, width, y + (int) (0.05 * heigth), paint);
		canvas.drawRect(x, y + heigth - (int) (0.05 * heigth), width, y
				+ heigth, paint);

		// render the cars
		for (Car car : cars) {
			car.render(canvas, paint);
		}
	}

	public ArrayList<Car> getCars() {
		return cars;
	}

	public void setCars(ArrayList<Car> cars) {
		this.cars = cars;
	}
}
